package com.xudow.app.dynamicstate_old.module.guide;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.jude.utils.JUtils;
import com.xudow.app.R;
import com.xudow.app.dynamicstate_old.data.DynamicModel;
import com.xudow.app.dynamicstate_old.data.server.ErrorTransform;
import com.xudow.app.dynamicstate_old.domain.entity.AttentionType;
import com.xudow.app.dynamicstate_old.widget.CircleTextView;
import com.xudow.app.newui.fragment.CourseFragment;
import com.xudow.app.newui.home.HomeActivity;
import com.xudow.app.ui.LoginActivity;
import com.xudow.app.util.PrefUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by ske on 2016/5/23.
 * 第三步
 */
public class TagActivity extends AppCompatActivity {
    @BindView(R.id.recyclerview)
    EasyRecyclerView recyclerview;
    @BindView(R.id.next)
    Button next;

    TagAdapter adapter;

    List<AttentionType> selectedAttention;

    @OnClick(R.id.back)
    void back(View view) {
        finish();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_guide_tag);
        ButterKnife.bind(this);

        setupView();
    }

    boolean isStudent;

    private void setupView() {
        isStudent = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("isStudent", false);
        selectedAttention = new ArrayList<AttentionType>();
        GridLayoutManager manager = new GridLayoutManager(this, 3);
        manager.setAutoMeasureEnabled(true);
        recyclerview.setLayoutManager(manager);
//        recyclerview.addItemDecoration(new SpacesItemDecoration(getResources().getDimensionPixelSize(R.dimen.content_margin)));
        recyclerview.setAdapter(adapter = new TagAdapter(this));
        next.setTextColor(getResources().getColor(isStudent ? R.color.role_student : R.color.role_parent));
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (selectedAttention.size() > 0) {
                    setAttentionType();
                } else {
                    Toast.makeText(TagActivity.this, "选择", Toast.LENGTH_SHORT).show();
                }
            }
        });
        getAttentionType();
    }

    private void setAttentionType() {
        int size = selectedAttention.size();
        int[] data = new int[size];
        for (int i = 0; i < size; i++) {
            data[i] = selectedAttention.get(i).getId();
        }
        String attentiontypeIds = new GsonBuilder()
                .excludeFieldsWithoutExposeAnnotation()
                .create()
                .toJson(data);
        String attentions;
        PreferenceManager.getDefaultSharedPreferences(this).edit().putString("attentiontype", attentions = new Gson().toJson(selectedAttention)).apply();
        PreferenceManager.getDefaultSharedPreferences(this).edit().putString("attentiontypeIds", attentiontypeIds).apply();
        PrefUtils.removeFirstLaunch(this);

        Intent intent6 = new Intent();
        intent6.setAction("com.dsw.data");
        intent6.putExtra("data", "data");
        sendBroadcast(intent6);

        if (getIntent().getBooleanExtra("isLogin", false)) {
            String grade = PreferenceManager.getDefaultSharedPreferences(TagActivity.this).getString("Grade", "[]");
            try {
                JSONArray array1 = new JSONArray(grade);
                for (int i = 0; i < array1.length(); i++) {
                    JSONObject o = (JSONObject) array1.get(i);
//                    o.remove("name");
                    o.remove("selected");
//                    o.remove("name");
                }
                grade = array1.toString();
                JSONArray array2 = new JSONArray(attentions);
                for (int i = 0; i < array2.length(); i++) {
                    JSONObject o = (JSONObject) array2.get(i);
//                    o.remove("name");
                    o.remove("createTime");
                    o.remove("selected");
                    o.remove("gradeList");
                }
                attentions = array2.toString();

            } catch (JSONException e) {
            }
            DynamicModel.getInstance().submitUserAttention(grade, attentions)
                    .compose(new ErrorTransform<>(ErrorTransform.ServerErrorHandler.NONE))
                    .subscribe(integer -> {
                        Intent intent=new Intent(TagActivity.this, HomeActivity.class);
                        //intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                        setResult(RESULT_OK);
                        finish();
                    });
        } else {
            startActivity(new Intent(TagActivity.this, HomeActivity.class));
            setResult(RESULT_OK);



            finish();
        }
    }

    private void getAttentionType() {
        String gradeIds = PreferenceManager.getDefaultSharedPreferences(this).getString("GradeIds", "");
        gradeIds = gradeIds.replace("[", "");
        gradeIds = gradeIds.replace("]", "");
        DynamicModel.getInstance().loadInterest(gradeIds)
                .compose(new ErrorTransform<>(ErrorTransform.ServerErrorHandler.TOAST))
                .subscribe(list -> {
                    adapter.clear();
                    adapter.addAll(list);
                    adapter.notifyDataSetChanged();
                });
    }

    class TagAdapter extends RecyclerArrayAdapter<AttentionType> {

        public TagAdapter(Context context) {
            super(context);
        }

        @Override
        public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
            return new TagViewHolder(parent);
        }
    }
    int i;
    class TagViewHolder extends BaseViewHolder<AttentionType> {

        @BindView(R.id.text_tag)
        CircleTextView tag;

        public TagViewHolder(ViewGroup parent) {
            super(parent, R.layout.item_guide_tag);
            ButterKnife.bind(this, itemView);
        }

        @Override
        public void setData(final AttentionType data) {
            tag.setText(data.getName());



            SharedPreferences sharedPreferences = TagActivity.this.getSharedPreferences("guanzhuid", Context.MODE_PRIVATE);
            setBackGround(data.isSelected());
            tag.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {


                    data.setSelected(!data.isSelected());
                    setBackGround(data.isSelected());
                    if (selectedAttention.contains(data)) {
                        selectedAttention.remove(data);
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        --i;
                        editor.remove("datagetType" + i);
                        editor.remove("datagetId" + i);
                        editor.remove("datasize" + i);
                        //editor.clear();
                        editor.commit();

                    } else {
                        selectedAttention.add(data);
                        SharedPreferences.Editor editor=sharedPreferences.edit();

                        Log.i("guanzhu", "ssssssssssssss" + data.getType());
                        Log.i("guanzhu", "ssssssssssssss" + data.getId());
                        editor.putInt("datagetType" + i, data.getType());
                        editor.putInt("datagetId" + i, data.getId()); /*sKey is an array*/

                        i++;
                        editor.putInt("datasize", i);
                        editor.commit();

                    }
                }
            });
        }

        private void setBackGround(boolean select) {
            if (select) {
                if (isStudent) {
                    tag.setBackgroundColor(getResources().getColor(R.color.role_student));
                    tag.setBorderColor(getResources().getColor(R.color.role_student));
                } else {
                    tag.setBackgroundColor(getResources().getColor(R.color.role_parent));
                    tag.setBorderColor(getResources().getColor(R.color.role_parent));
                }
                tag.setTextColor(getResources().getColor(R.color.white));
            } else {
                tag.setBackgroundColor(getResources().getColor(R.color.white));
                tag.setBorderColor(getResources().getColor(R.color.grey));
                tag.setTextColor(getResources().getColor(R.color.gray));
            }
        }
    }
}